import optparse
import subprocess
import logging
import sys
import os.path
import shutil
import fileinput
import codecs
from os.path import join, splitext, split, exists
from shutil import copyfile

basedir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
curdir = os.path.abspath('.')

compiler_path = os.path.join(basedir,'extension/compiler/compiler.jar')

closure_dir = os.path.join(basedir,'extension/closure')
deps_file = os.path.join(closure_dir,'closure/goog/deps.js')

projects_path = join(basedir,'projects/projects')

def quoteSpace(s):
    return s.replace(" ","' '")

def removeDupes(seq):
    # Not order preserving
    keys = {}
    for e in seq:
        keys[e.rstrip()] = 1
    return keys.keys()

def makeProjectPaths(add):
    lines = open(projects_path,'r').readlines()
    if len(add):
        lines.append(add)
    newlines = filter(lambda x: exists(join(basedir,x.rstrip())) and len(x.rstrip()),lines)
    newlines = removeDupes(newlines)
    
    f = open(projects_path,'w')
    f.write('\n'.join(newlines))
    f.close()
    
def escapeSpace(s):
    return s.replace(" ","\\ ")

def update():
    
    reldir = os.path.relpath(curdir,basedir)
    if reldir!='.':
        makeProjectPaths(reldir)
    
    print ('更新Closure库的 deps.js文件')
    
    paths = open(projects_path,'r').readlines()
    paths.append('src\n')
    paths.append('extension\n')
    
    opt = ' '.join(map(lambda x: '--root_with_prefix="'+quoteSpace(os.path.join(basedir,x.rstrip()))+'/ ../../../../'+x.rstrip()+'/"',paths))

    call = escapeSpace(os.path.join(closure_dir,'closure/bin/build/depswriter.py'))+' --root_with_prefix="'+\
        quoteSpace(closure_dir)+'/ ../../" '+opt+' --output_file="'+deps_file+'"'
        
    print (call)
    
    subprocess.call(call,shell=True)

def create(name):
    
    path = os.path.join(curdir,name)
    
    if exists(path):
        logging.error('目录%s已经存在',path)
        sys.exit(1) 
    
    name = os.path.basename(path)
    
    proj = os.path.relpath(path,basedir)
    
    os.makedirs(path)
    
    for root, dirs, files in os.walk(os.path.join(basedir,'src/templates/default')):
        for file in files:
            if file.find("__NAME__")!=-1 and file.endswith(('.js', '.html')):
                shutil.copy2(os.path.join(basedir,'src/templates/default', file), path)
    
    for root, dirs, files in os.walk(path):
        for fname in files:
            oldFname = fname;
            newname = fname.replace('__NAME__',name)
            fileObj = codecs.open(os.path.join(path,newname), "w", "utf-8" )
            for line in fileinput.input(os.path.join(path,oldFname),False,'',0,'r',fileinput.hook_encoded('utf-8')):
                line = line.replace('{__NAME__}',name)
                fileObj.write(line)
                print(line.rstrip())
            fileObj.close();
            os.remove(os.path.join(path,oldFname))
            
    print ('工程路径：%s' % proj)
    
    #写入工程文件
    if proj!='.' and proj!='projects\\'+name:
        makeProjectPaths(os.path.relpath(path,basedir))
    
    update()

def compile(name, dst):
    
    paths = open(projects_path,'r').readlines()
    paths.append('src\n')
    paths.append('extension\n')

    opt = ' '.join(map(lambda x: '--root="'+os.path.join(basedir,x.rstrip())+'/"',paths))
    
    call = escapeSpace(os.path.join(closure_dir,'closure/bin/build/closurebuilder.py'))+' '+opt+' --namespace="'+name+'" '+\
        '-o compiled'+' --output_file="'+dst+'.js"'+' -c '+compiler_path;
        
    print (call)
    
    subprocess.call(call,shell=True);

def main():
    usage = """用法: %prog [command] [options]
Commands:
    update                    更新Closure库的deps.js文件
    create [path/name]        建立新的工程
    compile [name] [outputname]           编译压缩工程"""
    
    parser = optparse.OptionParser(usage)
    
    (options, args) = parser.parse_args()
    
    if args[0]=='update':
        update()
    
    elif args[0]=='create':
        create(args[1])
        
    elif args[0]=='compile':
        compile(args[1],args[2]) 
    
    else:
        logging.error('没有此命令: %s',args[0])
        exit(1)
    
if __name__ == '__main__':
    main()